package com.geralt.im.server;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.BlockingQueue;

import com.geralt.im.jms.MessageQueueProducer;
import com.geralt.im.model.NeedReplyMessage;
import com.geralt.im.servercommand.ServerCommand;
import com.geralt.im.servercommand.impl.GetServerMessageCommand;
import com.geralt.im.servercommand.impl.StartServerCommand;
import com.geralt.im.servercommand.impl.StopServerCommand;

public class ServerCommandControler implements Runnable{
	BlockingQueue <NeedReplyMessage> requstQueue;
	public void run(){
		Properties props = new Properties();
		
		InputStream is = IMServer.class.getClassLoader().getResourceAsStream("Queue.properties");
		try {
			props.load(is);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String url = props.getProperty("url");
		String queue = props.getProperty("responseQueue");
		MessageQueueProducer sender = new MessageQueueProducer(url,queue);
		while(true){
			try {
				NeedReplyMessage commandMessage = requstQueue.take();
				System.out.println("get a server command: "+commandMessage.getContent());
				ServerCommand command = serverCommandParse(commandMessage.getContent());
				command.setUuid(commandMessage.getUuid());
				command.setSender(sender);
				command.excute();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	public static ServerCommand serverCommandParse(String commandString){
		switch (commandString) {
		case "START":
			return new StartServerCommand();
		case "STOP":
			return new StopServerCommand();
		case "INFO":
			return new GetServerMessageCommand();
		}
		return null;
	}
	/**
	 * @return the requstQueue
	 */
	public BlockingQueue<NeedReplyMessage> getRequstQueue() {
		return requstQueue;
	}
	/**
	 * @param requstQueue the requstQueue to set
	 */
	public void setRequstQueue(BlockingQueue<NeedReplyMessage> requstQueue) {
		this.requstQueue = requstQueue;
	}
	
}
